import {Component} from '@angular/core';
import {
  IonicPage,
  normalizeURL,
  NavController,
  NavParams,
  ViewController,
  ToastController,
  ActionSheetController,
  Platform,
  LoadingController
} from 'ionic-angular';
import {Camera} from '@ionic-native/camera'
import {File} from '@ionic-native/file'
import {FileTransfer, FileTransferObject} from '@ionic-native/file-transfer'
import {FilePath} from '@ionic-native/file-path'
import {
  baseCommon
} from '../../common/baseCommon';
import {
  Storage
} from '@ionic/storage'
import {AppConfig} from '../../app/app.config';
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams,
} from '@angular/http';

declare var cordova: any;//导入第三方的库定义到TS文件中
/**
 * Generated class for the ModifyPhotoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-modify-photo',
  templateUrl: 'modify-photo.html',
})
export class ModifyPhotoPage{

  lastImage: string = null;
  phone: any;
  sessionID: any;
  laterImgUrl: any = '';

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public viewCtrl: ViewController,
              public action: ActionSheetController,
              public camera: Camera,
              public transfer: FileTransfer,
              public file: File,
              public http: Http,
              public storage: Storage,
              public toastCtrl: ToastController,
              public filePath: FilePath,
              public loadingCtrl: LoadingController,
              public platform: Platform) {
    this.laterImgUrl = navParams.get('imageURL');

  }

  ionViewDidLoad() {
    // console.log('ionViewDidLoad ModifyPhotoPage');
    this.storage.get('phone').then(val => {
      this.phone = val;
    })
    this.storage.get('sessionID').then(val => {
      this.sessionID = val;
    })

  }

  ionViewDidEnter() {
    AppConfig.viewCtrl = this.viewCtrl;
  }

  dismiss() {
    this.viewCtrl.dismiss(this.laterImgUrl);
  }


  presentActionSheet() {
    let actionSheet = this.action.create({
      title: '选择图片',
      buttons: [
        {
          text: '从图片库选择',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        },
        {
          text: '使用相机',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        },
        {
          text: '取消',
          role: 'cancel'
        }
      ]
    });
    actionSheet.present();
  }

  /**
   * 得到图片
   *
   * @param {any} sourceType
   * @memberof ModifyPhotoPage
   */
  takePicture(sourceType) {
    //定义相机参数
    var options = {
      quality: 100,//图片的质量
      sourceType: sourceType,
      saveToPhotoAlbum: false,//是否保存到相册中
      correctOrientation: true//是否纠正拍摄的照片的方向
    };

    //获取图片的方法
    this.camera.getPicture(options).then((imagePath) => {
      //特别处理android平台的文件路径问题
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
        this.filePath.resolveNativePath(imagePath)//获取android平台下的真实的路径
          .then(filePath => {
            //获取正确的路径
            let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
            //获取正确的名字
            let currectName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));

            this.copyFileToLocalDir(correctPath, currectName, this.createFileName());

          })
      } else {
        //获取正确的路径
        let correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
        //获取正确的名字
        let currectName = imagePath.substring(imagePath.lastIndexOf('/') + 1);

        this.copyFileToLocalDir(correctPath, currectName, this.createFileName());
      }
    }, (err) => {
      baseCommon.showToast(this.toastCtrl, "选择图片出现错误，请稍后再试一下");
    })
  }

  /**
   * 将获取到的图片或者相机拍摄到的图片进行另存为，用于后期的图片上传使用
   *
   * @param {any} namePath
   * @param {any} currectName
   * @param {any} newFileName
   * @memberof ModifyPhotoPage
   */
  copyFileToLocalDir(namePath, currectName, newFileName) {
    this.file.copyFile(namePath, currectName, cordova.file.dataDirectory, newFileName)
      .then(success => {
        this.lastImage = newFileName
      }, (erroe) => {
        baseCommon.showToast(this.toastCtrl, "存储图片出现错误，你干了什么？请稍后再试一下！");
      });
  }

  /**
   * 为文件生成一个新的文件名
   *
   * @returns
   * @memberof ModifyPhotoPage
   */
  createFileName() {
    var d = new Date(),
      n = d.getTime(),
      newFileName = n + ".jpg";//拼接文件名
    return newFileName;
  }

  /**
   * 处理图片的路径为可以上传的路径
   *
   * @param {any} img
   * @returns
   * @memberof ModifyPhotoPage
   */
  public pathForImage(img) {
    if (img === null) {
      return '';
    } else {
      return normalizeURL(cordova.file.dataDirectory + img);
    }
  }

  /**
   * 上传图片
   *
   * @memberof ModifyPhotoPage
   */
  uploadImage() {
    var loading = baseCommon.showLoading(this.loadingCtrl, "上传中...");
    var targetPath = this.pathForImage(this.lastImage);
    var apiUrl = AppConfig.httpLoc + '/info/uploadFavicon';
    var filename = this.phone + ".jpg"; //定义上传后的文件名
    var options = {
      fileKey: "file",
      fileName: filename,
      chunkedMode: false,
      mimeType: "multipart/form-data",
      params: {'file': filename, 'sessionID': this.sessionID}
    };

    const fileTransfer: FileTransferObject = this.transfer.create();
    fileTransfer.upload(targetPath, apiUrl, options).then(data => {
      loading.dismiss();
      baseCommon.showToast(this.toastCtrl, "图片上传成功。");
      setTimeout(val => {
        this.dismiss();
      }, 1000)
    }, err => {
      loading.dismiss();
      baseCommon.showToast(this.toastCtrl, "图片上传发生错误，请重试。");
    });
  }
}
